#!/usr/bin/env ruby

# Copyright (c) 2010-2012 Microsoft Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#	http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require 'rubygems'
require 'ruby-aws'
require 'fileutils'

outfile = ARGV.pop
input  = []
result = []

ARGV.each_index do |i|
	if i % 2 == 0
		input  << ARGV[i]
	else
		result << ARGV[i]
	end
end

if ARGV.length < 5 || input.length != result.length
	$stderr.puts("Usage: #{$0} <input1> <result1> ... <inputN> <resultN> <result_merged>")
	exit
end

printf("Merging %s -> %s\n", result.join(', '), outfile)
printf("Merge files? (y/n) ")
response = STDIN.gets.chomp.downcase
if response != 'y'
	printf("Exiting...\n")
	exit
end

result_merged = []
input.each_index do |i|
	identifier_map = { }

	input[i] = Amazon::Util::DataReader.load(input[i], :Tabular)
	input[i].each do |line|
		line[:sentence]   = line[:sentence].to_s
		line[:algorithm]  = line[:algorithm].to_s
		line[:identifier] = line[:sentence] + '_' + line[:algorithm]
	end
	input[i].sort! { |a,b| a[:identifier] <=> b[:identifier] }
	input[i].each_index do |j|
		identifier_map[('ID' + j.to_s).to_sym] = input[i][j][:identifier].to_sym
	end

	result[i] = Amazon::Util::DataReader.load(result[i], :Tabular)
	result[i].each do |assignment|
		assignment.each_key do |id|
			if identifier_map.has_key?(id)
				assignment[ identifier_map[id] ] = assignment.delete(id)
			end
		end
	end

	result_merged += result[i]
end

if File.exist?(outfile)
	FileUtils.move(outfile, outfile + '.backup');
end

Amazon::Util::DataReader.save(outfile, result_merged, :Tabular)

